package com.yx.changdao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.mapper.CommunityBuildMapper;
import com.yx.changdao.common.utils.ExcelImportExportUtils;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.utils.IDCheck;
import com.yx.changdao.common.utils.SysUtils;
import com.yx.changdao.common.vo.BuildToDepVo;
import com.yx.changdao.common.vo.ImportShopVo;
import com.yx.changdao.service.*;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Description: <br/>
 * 社区建筑物表
 * <p>
 * <br/>
 * @Auther: flexible
 * @create 2020/04/02 13:47
 */
@Service
public class CommunityBuildServiceImpl extends ServiceImpl<CommunityBuildMapper, CommunityBuild> implements CommunityBuildService {

    /**
     * 网格信息库表服务
     */
    @Autowired
    private GridInfoService gridInfoService;
    /**
     * 社区建筑物表服务
     */
    @Autowired
    private CommunityBuildService communityBuildService;
    /**
     * 户的服务
     */
    @Autowired
    private CommunityBuildDetailService communityBuildDetailService;
    @Autowired
    private CommunityResidentService communityResidentService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DepartmentService departmentService;


    /**
     * 根据网格Id查询建筑物
     */
    @Override
    public List<CommunityBuild> getBuildByGridId(Integer regionId) {
        return this.list(new QueryWrapper<CommunityBuild>().lambda()
                .eq(CommunityBuild::getGridId, regionId)
                .orderByDesc(CommunityBuild::getCreateTime));
    }

    @Override
    public boolean removeBuildDetail(Integer id) {
        //户id
        List<Integer> buildDetailId = new ArrayList<>();
        List<CommunityBuildDetail> buildDetails = communityBuildDetailService.list
                (new QueryWrapper<CommunityBuildDetail>().eq(CommunityBuildDetail.BUILD_ID, id));
        if (buildDetails.size() == 0) {
            return true;
        }
        for (CommunityBuildDetail buildDetail : buildDetails) {
            buildDetailId.add(buildDetail.getId());
        }
        //居民id
        List<CommunityResident> residents = communityResidentService.list
                (new QueryWrapper<CommunityResident>().in(CommunityResident.BUILD_DETAIL_ID, buildDetailId));
        for (CommunityResident integer : residents) {
            integer.setBuildDetailId(0);
            //更新居民
            communityResidentService.updateById(integer);
        }
        //删除户
        boolean buildDetailRemove = communityBuildDetailService.remove
                (new QueryWrapper<CommunityBuildDetail>().in(CommunityBuildDetail.ID, buildDetailId));
        if (!buildDetailRemove) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> checkAndSave(MultipartFile communityBuildFile) throws AlertException {
        //不合格的
        List<CommunityBuild> failed = new ArrayList<>();
        List<CommunityBuild> successNum = new ArrayList<>();
        List<CommunityBuild> updateNum = new ArrayList<>();
        List<Integer> faildNum=new ArrayList<>();
        Integer[] num = {2};
        ExcelImportExportUtils.readExcel(CommunityBuild.class, communityBuildFile, (communityBuild) -> {
            num[0] = num[0] +1;
            try {
                if (Faster.isNull(communityBuild)) {
                    throw new AlertException();
                }
                if (Strings.isNotBlank(communityBuild.getContactPhone())) {
                    boolean matches = communityBuild.getContactPhone().matches("^1[0-9]{10}$");
                    if (matches == false) {
                        throw new AlertException(communityBuild.getContactPhone() + " 手机号格式不正确");
                    }
                }
                //验证字段
                if (Strings.isBlank(communityBuild.getBuildName())) {
                    throw new AlertException("楼宇/平房不能为空");
                }
                if(communityBuild.getDepName()==null){
                    String userId = SysUtils.currentUserId();
                    SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
                    if(sysUser==null){
                        throw new  AlertException("该帐号不存在");
                    }
                    Department one = departmentService.
                            getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, sysUser.getDepId()));
                    communityBuild.setDepId(sysUser.getDepId());
                    communityBuild.setDepName(one.getDepName());
                }else {
                    Department one = departmentService.
                            getOne(new QueryWrapper<Department>().eq(Department.DEP_NAME, communityBuild.getDepName()));
                    communityBuild.setDepId(one.getDepId());
                    communityBuild.setDepName(one.getDepName());
                }
                GridInfo gridInfo = gridInfoService.getOne
                        (new QueryWrapper<GridInfo>().eq(GridInfo.GRID_NUM, communityBuild.getGridNum()));
                if(gridInfo==null){
                    throw new AlertException("不存在该网格编号："+communityBuild.getGridNum());
                }
                CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                        .eq(CommunityBuild.GRID_ID, gridInfo.getId())
                        .eq(CommunityBuild.BUILD_NAME, communityBuild.getBuildName()));
                if (Strings.isBlank(communityBuild.getBuildCode())) {
                    if(one!=null){
                        throw new AlertException(one.getBuildName()+ "已存在");
                    }


                    communityBuild.setBuildType(0);
                    communityBuild.setGridId(gridInfo.getId());
                    communityBuild.setId(null);
                    save(communityBuild);
                    //新增楼编号
                    communityBuild.setBuildCode(communityBuild.getGridId()+"-"+communityBuild.getId());
                    boolean b1 = communityBuildService.updateById(communityBuild);
                    if(!b1){
                        throw new AlertException("社区建筑物添加失败");
                    }
                    successNum.add(communityBuild);
                } else {
                    List<CommunityBuild> list = communityBuildService.list(new QueryWrapper<CommunityBuild>()
                            .eq(CommunityBuild.BUILD_CODE, communityBuild.getBuildCode()));
                    if(list.size()==0){
                        throw new AlertException("不存在该条记录");
                    }
                    if(one!=null&&!one.getId().equals(list.get(0).getId())){
                        throw new AlertException(one.getBuildName()+ "已存在");
                    }
                    communityBuild.setBuildType(0);
                    communityBuild.setGridId(gridInfo.getId());
                    communityBuild.setId(list.get(0).getId());
                    communityBuildService.updateById(communityBuild);
                    updateNum.add(communityBuild);
                }
            } catch (Exception e) {
                failed.add(communityBuild);
                faildNum.add(num[0]);
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("saveNum", successNum.size());
        map.put("updateNum", updateNum.size());
        map.put("failedNum", failed.size());
        map.put("rows",faildNum);
        map.put("list", failed);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> checkAndSaveShop(MultipartFile communityBuildFile) throws AlertException {
        //不合格的
        List<ImportShopVo> failed = new ArrayList<>();
        List<ImportShopVo> successNum = new ArrayList<>();
        List<ImportShopVo> updateNum = new ArrayList<>();
        List<Integer> faildNum=new ArrayList<>();
        Integer[] num = {2};
        ExcelImportExportUtils.readExcel(ImportShopVo.class, communityBuildFile, (importShopVo) -> {
            num[0] = num[0] +1;
            try {
                if (Faster.isNull(importShopVo)) {
                    throw new AlertException();
                }
               /* if (Strings.isNotBlank(importShopVo.getContactPhone())) {
                    boolean matches = importShopVo.getContactPhone().matches("^1[0-9]{10}$");
                    if (matches == false) {
                        throw new AlertException(importShopVo.getContactPhone() + " 手机号格式不正确");
                    }
                }*/
                if(Strings.isNotBlank(importShopVo.getLinkIdCard())){
                    if (importShopVo.getLinkIdCard().length()!=15&&importShopVo.getLinkIdCard().length()!=18) {
                        throw new AlertException("身份证不合法");
                    }
                }

                if (Strings.isBlank(importShopVo.getShopName())) {
                    throw new AlertException("商铺名称名称不能为空");
                }
                if (Strings.isBlank(importShopVo.getGridNum())) {
                    throw new AlertException("网格编号不能为空");
                }
                if (Strings.isBlank(importShopVo.getGatehouseNumber())) {
                    throw new AlertException("门楼牌号不能为空");
                }
                if (Strings.isBlank(importShopVo.getContactPhone())) {
                    throw new AlertException("商铺联系人手机号不能为空");
                }
                if (Strings.isBlank(importShopVo.getShopContactPerson())) {
                    throw new AlertException("商铺联系人不能为空");
                }
                if (importShopVo.getResidents()==null) {
                    throw new AlertException("是否有居住户不能为空");
                }
                if (Strings.isBlank(importShopVo.getDepName())) {
                    throw new AlertException("走访单位不能为空");
                }

                GridInfo gridInfo = gridInfoService.getOne
                        (new QueryWrapper<GridInfo>().eq(GridInfo.GRID_NUM, importShopVo.getGridNum()));
                CommunityBuild one = communityBuildService.getOne(new QueryWrapper<CommunityBuild>()
                        .eq(CommunityBuild.GRID_ID, gridInfo.getId())
                        .eq(CommunityBuild.SHOP_NAME, importShopVo.getShopName()));

                if (gridInfo == null) {
                    throw new AlertException(importShopVo.getGridNum() + "  网格编号不存在");
                }
                CommunityBuild communityBuild = new CommunityBuild();
                communityBuild.setBuildType(1);
                communityBuild.setId(null);

                communityBuild.setGridId(gridInfo.getId());
                communityBuild.setBuildCode(importShopVo.getBuildCode());
                communityBuild.setGridNum(importShopVo.getGridNum());
                communityBuild.setShopName(importShopVo.getShopName());
                communityBuild.setBusinessScope(importShopVo.getBusinessScope());
                communityBuild.setShopContactPerson(importShopVo.getShopContactPerson());
                communityBuild.setContactPhone(importShopVo.getContactPhone());
                communityBuild.setGatehouseNumber(importShopVo.getGatehouseNumber());
                communityBuild.setResidents(importShopVo.getResidents());

                if(importShopVo.getDepName()==null){
                    String userId = SysUtils.currentUserId();
                    SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
                    if(sysUser==null){
                        throw new  AlertException("该帐号不存在");
                    }
                    Department department = departmentService.
                            getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, sysUser.getDepId()));
                    communityBuild.setDepId(sysUser.getDepId());
                    communityBuild.setDepName(department.getDepName());
                }else {
                    communityBuild.setDepName(importShopVo.getDepName());
                    Department department = departmentService.
                            getOne(new QueryWrapper<Department>().eq(Department.DEP_NAME, communityBuild.getDepName()));
                    communityBuild.setDepId(department.getDepId());
                    communityBuild.setDepName(department.getDepName());
                }
                if (Strings.isBlank(importShopVo.getBuildCode())) {
                    if(one!=null){
                        throw new AlertException(one.getShopName()+ "已存在");
                    }
                    save(communityBuild);
                    //新增楼编号
                    communityBuild.setBuildCode(communityBuild.getGridId()+"-"+communityBuild.getId());
                    boolean b1 = communityBuildService.updateById(communityBuild);
                    if(!b1){
                        throw new AlertException("社区建筑物添加失败");
                    }
                    successNum.add(importShopVo);
                } else {
                    List<CommunityBuild> list = communityBuildService.list
                            (new QueryWrapper<CommunityBuild>().eq(CommunityBuild.BUILD_CODE, importShopVo.getBuildCode()));
                    if(list.size()==0){
                        throw new AlertException("不存在该条记录");
                    }
                    if(one!=null&&!one.getId().equals(list.get(0).getId())){
                        throw new AlertException(one.getShopName()+ "已存在");
                    }
                    communityBuild.setId(list.get(0).getId());
                    communityBuildService.updateById(communityBuild);
                    updateNum.add(importShopVo);
                }
            } catch (Exception e) {
                faildNum.add(num[0]);
                failed.add(importShopVo);
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("saveNum", successNum.size());
        map.put("updateNum", updateNum.size());
        map.put("failedNum", failed.size());
        map.put("rows",faildNum);
        map.put("list", failed);
        return map;
    }

    @Override
    public Map<String, Object> checkAndSaveDep(MultipartFile communityBuildDep) throws AlertException {
        //不合格的
        List<BuildToDepVo> failed = new ArrayList<>();
        List<BuildToDepVo> successNum = new ArrayList<>();
        List<BuildToDepVo> updateNum = new ArrayList<>();
        ExcelImportExportUtils.readExcel(BuildToDepVo.class, communityBuildDep, (buildToDepVo) -> {
            try {
                if (Faster.isNull(buildToDepVo)) {
                    throw new AlertException();
                }
                CommunityBuild communityBuild = communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.BUILD_NAME, buildToDepVo.getBuildName()));
                if(communityBuild==null){
                    throw new AlertException("未查询到该楼栋");
                }
                Department department = departmentService.getOne(new QueryWrapper<Department>().eq(Department.DEP_ID, buildToDepVo.getDepId()));
                if(department==null){
                    throw new AlertException("未查询到该部门");
                }
                communityBuild.setDepId(department.getDepId());
                communityBuild.setDepName(department.getDepName());
                boolean b = communityBuildService.updateById(communityBuild);
                if(!b){
                    throw new AlertException("更新失败");
                }else {
                    updateNum.add(buildToDepVo);
                }

            } catch (Exception e) {
                failed.add(buildToDepVo);
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("saveNum", successNum.size());
        map.put("updateNum", updateNum.size());
        map.put("failedNum", failed.size());
        map.put("list", failed);
        return map;
    }


    @Override
    public Map<String, Object> getGridNameByBuildId(String buildCode) throws AlertException {
        Map<String, Object> map = new HashMap<>();
        CommunityBuild build =
                communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.BUILD_CODE, buildCode));
        if (build == null) {
            map.put("buildName", null);
            map.put("gridId", null);
            return map;
        }
        GridInfo gridInfo = gridInfoService.getOne(new QueryWrapper<GridInfo>().eq(GridInfo.ID, build.getGridId()));
        map.put("buildName", build.getBuildName());
        if(Faster.isNotNull(gridInfo)){
            map.put("gridId", gridInfo.getId());
        }
        return map;
    }
}
